﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.ComponentModel;
using System.ServiceProcess;
using Microsoft.Win32;

using System.Reflection;
using System.Diagnostics;
using ClimateControl.Infrastructure.Service;

namespace ClimateControl.Service
{
    /// <summary>
    /// Installer for application server
    /// </summary>
    [RunInstaller(true)]
    public class ClimateWindowsServiceInstaller : Installer
    {
        private ServiceProcessInstaller processInstaller;
        private ServiceInstaller serviceInstaller;

        /// <summary>
        /// Constructor
        /// </summary>
        public ClimateWindowsServiceInstaller()
        {
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller = new ServiceInstaller();

            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = ServiceHelper.GetWindowsServiceName();
            serviceInstaller.DisplayName = ServiceHelper.GetWindowsServiceName();

            Installers.Add(serviceInstaller);
            Installers.Add(processInstaller);
        }

        #region Installer Overrides

        /// <summary>
        /// Override this method so that once the service is installed, it is automatically
        /// started
        /// </summary>
        /// <param name="savedState"></param>
        protected override void OnCommitted(System.Collections.IDictionary savedState)
        {
            ServiceController service = null;

            try
            {
                base.OnCommitted(savedState);
                service = new ServiceController(ServiceHelper.GetWindowsServiceName());
                service.Start();
            }
            catch (Exception)
            {

            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                    service = null;
                }
            }
        }

        #endregion
    }
}
